package com.studymaster.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.RowMapperResultSetExtractor;
import org.springframework.stereotype.Repository;

import com.studymaster.dao.SmallPaperDao;
import com.studymaster.domain.SmallPaper;

@Repository
public class SmallPaperDaoImpl implements SmallPaperDao{

	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	private static final String INSERT_PAPER = "INSERT INTO smallpaper(senderid, sendername, papermessage, receiverid,date,type) VALUES(?,?,?,?,?,?)";
	
	protected RowMapper smallPaperRowMap = new RowMapper() {
		@Override
		public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
			SmallPaper sp = new SmallPaper();
			
			sp.setSenderId(rs.getString("senderid"));
			sp.setSenderName(rs.getString("sendername"));
			sp.setPaperMessage(rs.getString("papermessage"));
			sp.setReceiverId(rs.getString("receiverid"));
			sp.setDate(rs.getString("date"));
			sp.setType(rs.getInt("type"));

			return sp;
		}
	};
	
	
	@Override
	public List<SmallPaper> getPaperByReceiverId(String receiverid,String date) {
		// TODO Auto-generated method stub
		List<SmallPaper> smallpapers = null;
		String searchsql = "select * from smallpaper where receiverid = ? and date > ?";
		try{
			smallpapers = (List<SmallPaper>)jdbcTemplate.query(searchsql,
					new Object[]{receiverid,date},
					new RowMapperResultSetExtractor(smallPaperRowMap));

		}catch (Exception e) {
			// TODO: handle exception
		}
		return smallpapers;
	}

	@Override
	public boolean insertSmallPaper(SmallPaper sp) {
		// TODO Auto-generated method stub
		boolean mSuccess = true;
		try {
			jdbcTemplate.update(INSERT_PAPER, new Object[]{ sp.getSenderId(),
					sp.getSenderName(),sp.getPaperMessage(),sp.getReceiverId(),sp.getDate(),sp.getType()});
		} catch (Exception e) {
			// TODO: handle exception
			mSuccess = false;
		}
		return mSuccess;
	}

	@Override
	public List<SmallPaper> getPapersFromDB(String senderid, String receiverid,
			String date) {
		List<SmallPaper> smallpapers = null;
		String searchsql = "select * from smallpaper where senderid = ? and receiverid = ? and date > ?";
		try{
			smallpapers = (List<SmallPaper>)jdbcTemplate.query(searchsql,
					new Object[]{senderid,receiverid,date},
					new RowMapperResultSetExtractor(smallPaperRowMap));

		}catch (Exception e) {
			// TODO: handle exception
		}
		return smallpapers;
	}

}
